import wx from 'weixin-js-sdk'
import axios from 'axios'

import wechatConfig from './config'
import utils from './utils'

class ZGWeChatSDK {
    /**
     * 当前实例
     */
    static instance

    /**
     * 附带小工具
     */
    static utils = utils

    /**
     * 构造函数
     */
    constructor(config) {
        if (config != undefined) {
            wechatConfig.base.appID = config.appID
            wechatConfig.api.user_info_url = config.user_info_url
            wechatConfig.api.signature_url = config.signature_url
        }
    }

    /**
     * 获取单例
     */
    static getInstance(config) {
        if (false === this.instance instanceof this) {
            this.instance = new ZGWeChatSDK(config)
        }
        return this.instance
    }

    /**
     * 跳转授权页面
     */
    gotoAuthPage() {
        const appID = wechatConfig.base.appID
        const redirect_uri = location.href
        const scope = 'snsapi_userinfo'
        const url = `${wechatConfig.api.oAuth_code_url}?appid=${appID}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}#wechat_redirect`
        location.href = url
    }

    /**
     * 获取用户信息
     * @param {string}} code 
     */
    getUserInfo(code) {
        const url = `${wechatConfig.api.user_info_url}?code=${code}`
        return axios.get(url)
    }

    /**
     * 分享
     * @param {object} config 
     */
    share(config) {
        axios.get(wechatConfig.api.signature_url)
            .then(function (res) {
                const data = res.data
                console.log(data)
                wx.config({
                    debug: true,
                    appId: wechatConfig.base.appID,
                    timestamp: data.timestamp,
                    nonceStr: data.nonceStr,
                    signature: data.signature,
                    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
                })
            })
            .catch(function (err) {
                console.log(err)
            })
        wx.ready(function () {
            // 分享朋友
            wx.onMenuShareAppMessage(config)
            // 分享朋友圈
            wx.onMenuShareTimeline(config)
        })
    }
}

window.ZGWeChatSDK = ZGWeChatSDK